<?php

namespace App\Service\User\v1_2_8;

use App\Constants\ErrorCode;
use App\Event\InviteEvent;
use App\Model\Guild\GuildHost;
use App\Model\Guild\GuildManage;
use App\Model\User;
use App\Model\UserProfile;
use App\Model\UserProfilePersonal;
use App\Service\User\UserBaseService;
use Psr\EventDispatcher\EventDispatcherInterface;

/**
 * 邀请绑定
 */
class InviteBindService extends UserBaseService
{
    protected function RoVerifyList()
    {
        return [
            'invite_code' => 'required|string'
        ];
    }

    public function handle()
    {
        $userId = $this->getUserId();
        $inviteCode = $this->request->input('invite_code', '');
        //限制用户注册时间
        $lmtMinutes = config('act.invite.bind_expire');
        $user = User::getUser($userId);
        $regTime = strtotime((string)$user->created_at);
        if ((time() - $regTime) > $lmtMinutes * 60) {
            return $this->setError(ErrorCode::BIND_INVITE_EXP, '暂无法绑定邀请关系～');
        }
        //是否公会ID
        if ($guildInfo = GuildManage::getInfoByGuildId($inviteCode)) {
            $profile = UserProfile::getProfile($userId);
            //非主播身份，无法绑定工会
            if (!UserProfile::checkRoleHost($profile->role)) {
                return $this->setError(ErrorCode::BIND_INVITE_INVALID, '暂未实名认证，无法绑定该邀请码～');
            }
            $vrf = UserProfilePersonal::isRealnameVerified(UserProfilePersonal::getProfile($inviteCode));
            GuildHost::bindHost($userId, $guildInfo['id'], $vrf, $profile->user_profile_id);
            return ['result' => 1];
        }

        $profile = UserProfile::getInfoByProfileId($inviteCode);
        if (!$profile || $profile->user_id == $userId) {
            return $this->setError(ErrorCode::BIND_INVITE_INVALID, '该邀请码无效！');
        }
        $selfProfile = UserProfile::getProfile($userId);
        if ($selfProfile->invite_code) {
            return $this->setError(ErrorCode::BINDED_INVITE, '你已经绑定过邀请人，无法再次绑定！', $userId);
        }
        //绑定
        UserProfile::updateInfo($userId, ['invite_code' => $inviteCode]);
        //邀请事件
        make(EventDispatcherInterface::class)->dispatch(new InviteEvent($profile->user_id, $userId, $profile));
        return ['result' => 1];
    }
}
